<template>
  <main-card :title="'数据标注'" :loading="loading" :show-screen-space="false" :online-lab="true">
    <template #tool-btn>
      <a-space :size="8">
        <a-button type="text" class="icon-buttons" @click="openOnlineExportListModel">
          <i class="iconfont icon-tasklist-line" style="font-size: 18px"></i>
        </a-button>
        <a-button @click="goTagGroup()">
          <span class="text">标签组管理</span>
        </a-button>
        <a-button type="primary" @click="goAdd">
          <span class="text">创建任务</span>
        </a-button>
      </a-space>
    </template>

    <div class="mb-48 fbc">
      <a-cascader
        v-model:value="taskTypeCascaderValue"
        placeholder="全部类型"
        :options="taskTypeOptions"
        @change="onTaskTypeCascaderChange"
      />

      <div class="flex-1"></div>
      <g-input
        v-model:value="pageForm.name"
        search
        class="h-36"
        placeholder="请输入名称"
        style="width: 328px"
        @keyup.enter="getDataList({ offset: 1 })"
      />
    </div>

    <a-table
      :columns="tableColumns"
      :data-source="taskList"
      :custom-row="(r: any) => ({ onClick: () => goDetail(r) }) "
      :pagination="false"
      :style="{ width: '100%' }"
      @change="tableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'markType'">
          <div
            :class="{
              'task-type-blue': record.markType === DmpTaskType.text,
              'task-type-red': record.markType === DmpTaskType.img
            }"
          >
            {{ `${getTaskTypeName(record.markType)}>${getTaskTypeName(record.markSubType)}` }}
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'progress'">
          <template v-if="record.status === 2"> 数据准备中... </template>
          <div v-else class="fbc">
            <a-progress :percent="Number((record.success / record.count) * 100)" :show-info="false" style="width: 168px" size="small" />
            <span class="mr-12"> {{ record.success }}/{{ record.count }}</span>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dateFormat(record[column.dataIndex]) }}
        </template>
        <template v-else-if="column.dataIndex === 'status'">
          <div v-if="record.status === 1" class="table__status">未标注</div>
          <div v-else-if="record.status === 2" class="table__status">数据准备中...</div>
          <div v-else-if="record.status === 3" class="table__status">标注中...</div>
          <div v-else-if="record.status === 4" class="table__status">标注完成</div>
          <div v-else-if="record.status === 5" class="table__status error">数据准备失败</div>
          <div v-else-if="record.status === 6" class="table__status error">数据准备超时</div>
        </template>

        <template v-else-if="column.dataIndex === 'tools'">
          <a-dropdown @click.stop>
            <a-button :data-share="record.createType === 1" type="text" class="icon-only-btn" @click.stop>
              <i class="iconfont icon-more-line"></i>
            </a-button>
            <template #overlay>
              <a-menu>
                <a-menu-item v-if="checkPermissions(record.createType, record.readOnly)" @click="editGroup(record as DmpTask)">
                  <a>编辑任务</a>
                </a-menu-item>
                <template v-if="[1, 3, 4].includes(record.status)">
                  <a-menu-item @click="exportTask(record, 'online')">
                    <a>在线导出</a>
                  </a-menu-item>
                  <a-menu-item @click="exportTask(record, 'local')">
                    <a>本地导出</a>
                  </a-menu-item>
                </template>
                <a-menu-item
                  v-if="checkPermissions(record.createType, record.readOnly) && record.isInput"
                  class="menu-icon-item"
                  @click.stop="handleToImportPage(record as any)"
                >
                  导入
                </a-menu-item>
                <a-menu-item
                  v-if="checkPermissions(record.createType, record.readOnly)"
                  class="menu-icon-item"
                  @click.stop="handleOpenShareModal(record)"
                >
                  分享
                </a-menu-item>
                <a-menu-item v-if="checkPermissions(record.createType, record.readOnly)" @click="openDeleteTaskModal(record as DmpTask)">
                  <a>删除</a>
                </a-menu-item>
                <a-menu-item class="menu-icon-item" @click.stop="handleOpenImportRecord(record as any)"> 导入记录 </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
        <template v-else>
          {{ replaceEmptyStr(record[column.dataIndex as string]) }}
        </template>
      </template>
    </a-table>
    <g-pagination v-model:offset="pageForm.offset" v-model:limit="pageForm.limit" :total="pageForm.total" @change="getDataList" />
  </main-card>

  <!-- 删除任务 -->
  <delete-confirm-dialog
    v-model:show="isDeleteDialogShow"
    :confirm-name="currentDeleteTaskItem?.name"
    :loading="confirmLoading"
    @ok="onOkDeleteTask"
  />

  <edit-task-form ref="editModelRef" :after-close-fn="getDataList" />

  <!-- 导出 -->
  <online-export-form ref="onlineExportFormRef" :export-after="openOnlineExportListModel" />
  <local-export-form ref="localExportFormRef" />

  <!-- 在线导出列表 -->
  <online-export-list ref="onlineExportListRef" />
  <!-- <task-list-drawer /> -->
  <import-record ref="importRecordRef" />

  <!-- 分享 -->
  <share-modal
    ref="shareModalRef"
    :submit-api="dmpTaskApi.share"
    :remove-user-api="dmpTaskApi.removeShareUser"
    :get-list-api="dmpTaskApi.getShareList"
  />
</template>

<script lang="ts" setup>
  import { message, TableProps } from 'ant-design-vue'
  import { dateFormat } from 'g6-fn'
  import { ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRouter } from 'vue-router'

  import DeleteConfirmDialog from '@/components/DeleteConfirmDialog/index.vue'
  import ShareModal from '@/components/ShareModal/index.vue'
  import useList from '@/hooks/use-list'
  import { dmpTaskApi } from '@/services/api'
  import { filterTableColumns, replaceEmptyStr } from '@/utils'
  import { checkPermissions } from '@/utils/share'

  import EditTaskForm from '../components/EditTaskForm.vue'
  import { taskTypeOptions } from '../options'
  import { DmpSubTaskType, DmpTask, DmpTaskType } from '../types'
  import { getTaskTypeName } from '../utils'
  import ImportRecord from './components/ImportRecord.vue'
  import LocalExportForm from './components/LocalExportForm.vue'
  import OnlineExportForm from './components/OnlineExportForm.vue'
  import OnlineExportList from './components/OnlineExportList.vue'
  // import TaskListDrawer from './components/TaskListDrawer/index.vue'
  // import { useTaskListDrawerStore } from './components/TaskListDrawer/store'

  const router = useRouter()
  // const taskListDrawerStore = useTaskListDrawerStore()

  interface FormState {
    name: string
    status: string
    markSubType: DmpSubTaskType | ''
    columns: string
    order: string
  }

  const tableColumns = ref(
    filterTableColumns([
      {
        title: '名称',
        dataIndex: 'name',
        width: 180
      },
      {
        title: '类型',
        dataIndex: 'markType',
        width: 150
      },
      {
        title: '状态',
        dataIndex: 'status',
        width: 140
      },
      {
        title: '描述',
        dataIndex: 'description'
      },
      {
        title: '标注数',
        dataIndex: 'labCount',
        width: 80
      },
      {
        title: '完成进度',
        dataIndex: 'progress',
        width: 320
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        isSort: true,
        width: 190
      },
      {
        title: '操作',
        dataIndex: 'tools',
        width: 63
      }
    ])
  )

  const {
    getDataList,
    loading,
    pageForm,
    dataList: taskList
  } = useList<FormState, DmpTask>(
    dmpTaskApi.list,
    {
      markSubType: '',
      name: '',
      status: '',
      columns: 'createTime',
      order: ''
    },
    {
      isOpenSync: true
    }
  )

  const goAdd = () => {
    router.push(`/dmp/add`)
  }

  const goTagGroup = () => {
    router.push(`/dmp/tag-group-list`)
  }

  const goDetail = (record: { markSubType: DmpSubTaskType; id: string; status: number }) => {
    console.log(record, 'taskType')
    const typePath: string | undefined = {
      // 图像分类
      [DmpSubTaskType.imgClass]: '/dmp/detail/dmp-img/img-class',
      // 图像分类
      [DmpSubTaskType.imgObjDetect]: '/dmp/detail/dmp-img/img-obj-detect',
      // 文本分类
      [DmpSubTaskType.textClass]: '/dmp/detail/dmp-text/text-class',
      // 命名实体
      [DmpSubTaskType.textNamedEntity]: '/dmp/detail/dmp-text/named-entity',
      // // 文本三元组
      [DmpSubTaskType.textTriple]: '/dmp/detail/dmp-text/text-triplet',
      // // 文本相似度
      [DmpSubTaskType.textSimilarity]: '/dmp/detail/dmp-text/text-similarity'
    }[record.markSubType]

    //准备中不可点击
    if (record.status === 0 || record.status === 2) {
      return
    }
    window.open(`${typePath}/${record.id}`)
  }

  const tableChange: TableProps['onChange'] = (pagination, filters: any, sorter: any) => {
    pageForm.value.status = filters.status?.length ? filters.status[0] : ''
    pageForm.value.columns = sorter.field === 'updateTime' ? 'updateTime' : 'createTime'
    pageForm.value.order = sorter.order === 'ascend' ? 'asc' : 'desc'
    getDataList({ offset: 1 })
  }

  /* 任务类型切换 ----------------------------------------------------------------- */
  const taskTypeCascaderValue = ref([])
  const onTaskTypeCascaderChange = () => {
    const markSubType = taskTypeCascaderValue.value ? taskTypeCascaderValue.value[1] : ''

    getDataList({
      markSubType: markSubType,
      offset: 1
    })
  }

  /* 编辑任务------------------------------------------------------------------------------------------------- */
  const editModelRef = ref<InstanceType<typeof EditTaskForm>>()
  const editGroup = (record: any) => {
    editModelRef.value?.open(record)
  }
  /* 删除测试任务 ----------------------------------------------------------------- */
  const currentDeleteTaskItem = ref<DmpTask>()
  const isDeleteDialogShow = ref(false)

  const openDeleteTaskModal = (item: DmpTask) => {
    currentDeleteTaskItem.value = item
    isDeleteDialogShow.value = true
  }
  const { loading: confirmLoading, runAsync: runDelDmpTask } = useRequest(dmpTaskApi.del)
  const onOkDeleteTask = async () => {
    await runDelDmpTask({}, { isAddUid: true, urlParams: { id: currentDeleteTaskItem.value?.id } })
    message.success('操作成功')
    isDeleteDialogShow.value = false
    getDataList()
  }

  /* 导出 ----------------------------------------------------------------------------------------------- */
  const onlineExportFormRef = ref()
  const localExportFormRef = ref()
  const onlineExportListRef = ref()

  const openOnlineExportListModel = () => {
    onlineExportListRef.value.open()
    // taskListDrawerStore.changeTaskListOptions({ open: true })
  }

  const exportTask = async (record: any, type: 'local' | 'online') => {
    if (type === 'local') {
      localExportFormRef.value.open(record)
      return
    }
    if (type === 'online') {
      onlineExportFormRef.value.open(record)
    }
  }

  const importRecordRef = ref<InstanceType<typeof ImportRecord>>()
  // 导入
  const handleToImportPage = (record: { markSubType: DmpSubTaskType; id: string }) => {
    router.push(`/dmp/import-data/${record.id}?markSubType=${record.markSubType}`)
  }
  // 导入记录
  const handleOpenImportRecord = (record: any) => {
    importRecordRef.value?.open(record.id, checkPermissions(record.createType, record.readOnly))
  }

  /* 分享 ----------------------------------------- --------------------------------*/
  const shareModalRef = ref<InstanceType<typeof ShareModal>>()
  const handleOpenShareModal = (item: any) => {
    shareModalRef.value?.open({
      id: item.id
    })
  }
  /* ----------------------------------------------------------------------------------------------- */
  getDataList()
</script>

<style lang="less" scoped>
  .add-btn {
    display: flex;
    align-items: center;
    font-size: 16px;

    .icon {
      line-height: 16px;
      margin-right: 10px;
    }

    .text {
      transform: translate(0, -1px);
    }
  }

  .task-type-blue {
    display: inline-block;
    padding: 3px 6px;
    margin-left: -15px;
    color: rgba(70, 134, 237, 1);
    background-color: rgba(70, 134, 237, 0.08);
    border: 1px solid rgba(0, 0, 0, 0.05);
    border-radius: 6px;
    line-height: 22px;
  }

  .task-type-red {
    display: inline-block;
    padding: 3px 6px;
    margin-left: -15px;
    color: rgba(214, 24, 96, 1);
    background-color: rgba(214, 24, 96, 0.08);
    border: 1px solid rgba(0, 0, 0, 0.05);
    border-radius: 6px;
    line-height: 22px;
  }

  .icon-buttons {
    padding: 0;
    margin-right: 8px;
    width: 36px;
  }

  .icon-loader {
    animation: rotate 1000ms linear infinite;
  }
</style>
